package com.distribute.framework.plugin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.distribute.framework.core.sql.redis.RedisSupport;
import com.distribute.framework.plugin.Notify.Listener;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class RedisMQ extends BaseMQ{
	
	public static final String defaultRedisFlag = "redis.framework";
	
	public static RedisSupport defaultRedisSupport = RedisSupport.getRedis(defaultRedisFlag);
	
	public static Map<String,List<Listener>> listeners = new HashMap();

	@Override
	public void sendTextMessage(String flag, String destinationName, String message, Boolean isP2P) {
		Jedis jedis = defaultRedisSupport.getJedis();
		try{
			jedis.publish(destinationName, message);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if(jedis!=null){
				defaultRedisSupport.retJedis(jedis);
			}
		}
	}

	@Override
	public void addMessageListener(String flag, final String[] destinationNames, final Listener notifyListener, Boolean isP2P) {
		new Thread(){
			public void run(){
				Jedis jedis = defaultRedisSupport.getJedis();
				try{
					jedis.subscribe(new JedisPubSub(){
						@Override
					    public void onMessage(String channel, String message) {//收到消息会调用
							try{
								notifyListener.execute(message);
							}catch(Exception x){
								x.printStackTrace();
							}
					    }
					}, destinationNames);
				}catch(Exception ex){
					ex.printStackTrace();
				}finally{
					if(jedis!=null){
						defaultRedisSupport.retJedis(jedis);
					}
				}
			}
		}.start();
	}

}